

import de.yuv.gsak2iphone.components.*;
import de.yuv.gsak2iphone.events.MyMenuItemEvent;

import flash.events.Event;
import flash.events.MouseEvent;
import flash.filesystem.*;

import mx.containers.Canvas;
import mx.events.IndexChangedEvent;

	
public var globalPrefs:XmlPreferences;

public var prefsFile:File;
public var prefsXML:XML;
public var stream:FileStream;

public var directory:File = File.documentsDirectory;
public var nextLocation:String;

public function appComplete():void
{ 
	if (globalPrefs.preferences.windowState.@width.toString() != ""){
		nativeWindow.x = globalPrefs.preferences.windowState.@x;
		nativeWindow.y = globalPrefs.preferences.windowState.@y;
		nativeWindow.width = globalPrefs.preferences.windowState.@width;
		nativeWindow.height = globalPrefs.preferences.windowState.@height;
	}
	nativeWindow.addEventListener(Event.CLOSING, windowClosingHandler);
	exitKnob.addEventListener(MouseEvent.CLICK, windowClosingHandler);
	menuKnob.addEventListener(MouseEvent.CLICK, handleMenuKnob);
	addKnob.addEventListener(MouseEvent.CLICK, handleAddKnob);
	infoKnob.addEventListener(MouseEvent.CLICK, handleInfoKnob);
	
	
	
	myStack.addEventListener(IndexChangedEvent.CHANGE, handleViewStackChange);
	
	
}


public function init():void{
	globalPrefs = new XmlPreferences('preferences.xml');
	globalPrefs.load();
}


public function windowClosingHandler(event:Event):void {
	event.preventDefault();
	globalPrefs.preferences.windowState.@width = nativeWindow.width;
	globalPrefs.preferences.windowState.@height = nativeWindow.height;
	globalPrefs.preferences.windowState.@x = nativeWindow.x;
	globalPrefs.preferences.windowState.@y = nativeWindow.y;
	globalPrefs.preferences.windowState.@alwaysinfront = nativeWindow.alwaysInFront;
	globalPrefs.save();
	exit();
}

public function handleMenuKnob(event:Event):void {
	myStack.selectedChild = myMenu;
}

public function handleInfoKnob(event:Event):void {
	myStack.selectedChild = myInfo;
}

public function handleAddKnob(event:Event):void {
	try
	{
		trace("lastDir"+globalPrefs.preferences.gsakDirs.@lastDir)
		myStack.selectedChild = myAdd;
		try {
			var temp:File = new File(globalPrefs.preferences.gsakDirs.@lastDir);
			if (temp.exists){
				directory.nativePath = globalPrefs.preferences.gsakDirs.@lastDir;
			}
		}
		catch (error:Error)
		{
		    trace("Failed:", error.message)
		}
	    directory.browseForDirectory("Select Directory");
	    directory.addEventListener(Event.SELECT, directorySelected);
	}
	catch (error:Error)
	{
	    trace("Failed:", error.message)
	}

}

public function directorySelected(event:Event):void 
{
	
	trace('directorySelected')
    directory = event.target as File;
    // TODO: Suchen nach index.html oder Fehlermeldung
    newDir.text = directory.nativePath;
    dirName.text = directory.name;
    /*
    var files:Array = directory.getDirectoryListing();
    for(var i:uint = 0; i < files.length; i++)
    {
        trace(files[i].name);
    }
    */
}

public function saveDir():void 
{
	//trace('saveDir')
	//trace("|"+globalPrefs.preferences.gsakDirs.length()+"|");
	if (globalPrefs.preferences.gsakDirs.length() == 0){
		var myXML:XML = <gsakDirs />
		globalPrefs.preferences.addChild = myXML;
		
	}
	globalPrefs.preferences.gsakDirs.@lastDir = newDir.text;
	myXML = <item />
	globalPrefs.preferences.gsakDirs.addChild = myXML;
	var nr:uint = globalPrefs.preferences.gsakDirs.item.length()-1;
	globalPrefs.preferences.gsakDirs.item[nr] = newDir.text;
	globalPrefs.preferences.gsakDirs.item[nr].@name = dirName.text;
	//globalPrefs.preferences.gsakDirs[1].name = 'zwei';
	handleMenuIsShown();
	myStack.selectedChild = myMenu;
	

}

public function handleMenuIsShown():void{
	if (myMenuVBox != null){
		trace("handleMenuIsShown");
		var __childs:Array = myMenuVBox.getChildren();
		trace(__childs.length);
		for (var i:uint=0; i<__childs.length; i++){
			var temp1:MyMenuItem = __childs[i] as MyMenuItem;
			temp1.removeEventListener(MyMenuItemEvent.CLICKEDCONVERT,handleMenuClick);
			temp1.removeEventListener(MyMenuItemEvent.CLICKEDVIEW,handleMenuClick);
			temp1.removeEventListener(MyMenuItemEvent.CLICKEDDELETE,handleMenuClick);
		}
		myMenuVBox.removeAllChildren();
		for each (var property:XML in globalPrefs.preferences.gsakDirs.item)
		{
			var temp:MyMenuItem = new MyMenuItem;
			temp.menuLabel = property.@name;
			temp.directory = property.valueOf()
			temp.xmlindex = property.childIndex();
			myMenuVBox.addChild(temp);
			temp.addEventListener(MyMenuItemEvent.CLICKEDCONVERT,handleMenuClick);
			temp.addEventListener(MyMenuItemEvent.CLICKEDVIEW,handleMenuClick);
			temp.addEventListener(MyMenuItemEvent.CLICKEDDELETE,handleMenuClick);
	}
	}
}

public function handleMenuClick(__ev:MyMenuItemEvent):void{
	trace(__ev.target+" - "+__ev.type);
	var __target:MyMenuItem = __ev.target as MyMenuItem;
	switch (__ev.type){
		case MyMenuItemEvent.CLICKEDVIEW:
			trace(__target.directory);
			var __file:File = new File(__target.directory+"/_1index.htm");
			trace(__file.url);
			nextLocation = __file.url
			myStack.selectedChild = myBrowser;
			
		break;
		case MyMenuItemEvent.CLICKEDDELETE:
			delete(globalPrefs.preferences.gsakDirs.item[__target.xmlindex])
			handleMenuIsShown();
		break;
		case MyMenuItemEvent.CLICKEDCONVERT:
			convertFilesInDirectory(__target.directory,__target);
			//handleMenuIsShown();
		break;
		
	}
	
}


public function handleBrowserIsShown():void{
	trace("handleBrowserIsShown");
	htmlControl.location = nextLocation;
}




public function handleViewStackChange(ev:IndexChangedEvent):void{
	
	trace("handleViewStackChange"+ev.newIndex)
	var newView:Canvas = myStack.getChildAt(ev.newIndex) as Canvas;
	myHeadline.text = newView.label;
	backKnob.enabled = false;
	forwardKnob.enabled = false;
	switch (ev.newIndex){
		case 1: //
			if (htmlControl != null) handleBrowserIsShown();
			backKnob.enabled = true;
			forwardKnob.enabled = true;
		break;
		case 2: //menu
			//handleMenuIsShown();
		break;
		
	}
}

public function convertFilesInDirectory(__Directory:String,__menuItem:MyMenuItem):void{
	trace('convertFilesInDirectory');
	var __dir:File = new File(__Directory);
	copyFile('iPhoneArrow.png',__dir);
	copyFile('iphonenav.css',__dir);
	copyFile('iPhoneToolbar.png',__dir);
	var __temp:String = __menuItem.myLabel.text;
	var list:Array = __dir.getDirectoryListing();
	__menuItem.myLabel.text = "Working...please wait..."
	for (var i:uint = 0; i < list.length; i++) {
		//__menuItem.myLabel.text = __temp+" "+Math.floor((list.length-1)/i*100)+"%";
	    if (list[i].extension == "htm"){
	    	//trace(list.length+" - "+i);
	    	parseHtml(list[i]);
	    	
	    }
	}
	__menuItem.myLabel.text = __temp;
	var __file:File = new File(__menuItem.directory+"/_1index.htm");
	nextLocation = __file.url
	myStack.selectedChild = myBrowser;
}

public function copyFile(__FileName:String,__to:File):void{
	var sourceFile:File = File.applicationDirectory;
	sourceFile = sourceFile.resolvePath("copyFiles/"+__FileName);
	//trace(sourceFile.url);
	//trace(__to.url);
	var destination:File = new File();
	destination = __to.resolvePath(__FileName);
	//trace(destination.url);
	sourceFile.copyTo(destination, true);
}

public function parseHtml(__htmlFile:File):void{
	var __stream:FileStream = new FileStream();
	__stream.open(__htmlFile, FileMode.READ);
	var __htmlSource:String = __stream.readUTFBytes(__stream.bytesAvailable);
	__stream.close();
	var __search:RegExp = /\<body/;  
	var __replace:String = '<meta name = "viewport" content = "width = device-width">\n';
	__replace += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n';
	__replace += '<style type="text/css" media="screen">@import "iphonenav.css";</style>\n';
	__replace += '<body';
	__htmlSource = __htmlSource.replace(__search, __replace);
	
	switch (__htmlFile.name){
		case "_2NameIndex.htm":
			__search = /<a href="(.*)">(.*)<\/a> (.*)<br>/gi;
			__replace = '<li><a href="$1">$3 <small>($2)</small></a></li>';
			__htmlSource = __htmlSource.replace(__search, __replace);
			
			__search = /<p><a name="(.*)">(.*)<\/a> &nbsp;&nbsp;&nbsp; <a href="#top">Top <\/a><br>/gi;
			__replace = '</ul><h1><a name="$1">$2</a></h1><ul selected="true">';
			__htmlSource = __htmlSource.replace(__search, __replace);
		break;
		
		case "_2PlacedBy.htm":
			__search = /<a href="(.*)">(.*)<\/a> (.*)<br>/gi;
			__replace = '<li><a href="$1">$3 <small>($2)</small></a></li>';
			__htmlSource = __htmlSource.replace(__search, __replace);
			
			// <b>Adam Riese</b> &nbsp;&nbsp;&nbsp; <a href="#top">Top </a><br>
			__search = /<b>(.*)<\/b> &nbsp;&nbsp;&nbsp; <a href="#top">Top <\/a><br>/gi;
			__replace = '</ul><h1>$1</h1><ul selected="true">';
			__htmlSource = __htmlSource.replace(__search, __replace);
		break;
		case "_2CodeIndex.htm":
			__search = /<a href="(.*)">(.*)<\/a> (.*)<br>/gi;
			__replace = '<li><a href="$1">$2 <small>($3)</small></a></li>';
			__htmlSource = __htmlSource.replace(__search, __replace);
			
			__search = /<p><a name="(.*)">(.*)<\/a> &nbsp;&nbsp;&nbsp; <a href="#top">Top <\/a><br>/gi;
			__replace = '</ul><h1><a name="$1">$2</a></h1><ul selected="true">';
			__htmlSource = __htmlSource.replace(__search, __replace);
			
			__search = /<p>(\s|\f)*<li/gi;
			__replace = '<p><ul><li';
			__htmlSource = __htmlSource.replace(__search, __replace);
		break;
		
		
		case "_1index.htm":
		case "index.htm":
		// <a href="_2NameIndex.htm">Name</a><br>
			__search = /<a href="(.*)">(.*)<\/a><br>/gi;
			__replace = '<li><a href="$1">$2</a></li>';
			__htmlSource = __htmlSource.replace(__search, __replace);
			
			__search = /<p>(\s|\f)*<li/gi;
			__replace = '<p><ul><li';
			__htmlSource = __htmlSource.replace(__search, __replace);
			
			__search = /<(\/*)center>/gi;
			__replace = '';
			__htmlSource = __htmlSource.replace(__search, __replace);
		break;
		

		
	}
	
	__htmlSource = '<?xml version="1.0" encoding="ISO-8859-1" ?>\n'+__htmlSource;
	__stream.open(__htmlFile, FileMode.WRITE);
	__stream.writeUTFBytes(__htmlSource);
	__stream.close();
	
	
	
	//trace(__htmlSource)
}



